package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.controller.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("FillerRestController")
public class FillerRestController extends CmiEmaController {

	/**
	 * Create a new Filler entity
	 * 
	 */
	@RequestMapping(value = "/newFiller", method = RequestMethod.POST)
	@ResponseBody
	public Object newFiller(@RequestBody Filler filler) {
		fillerService.saveFiller(filler);
		return JSONObject.parse(cmiPsonService.toJsonString(fillerDAO.findFillerByPrimaryKey(filler.getId()), 2));
	}

	@RequestMapping(value = "/restNewFiller", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewFiller(@RequestBody String fillerJson) {
		Filler filler = new Gson().fromJson(fillerJson, Filler.class);
		appendReferences(filler);
		fillerService.saveFiller(filler);
		return JSONObject.parse(cmiPsonService.toJsonString(fillerDAO.findFillerByPrimaryKey(filler.getId()), 2));
	}

	@RequestMapping(value = "/saveFiller", method = RequestMethod.PUT)
	@ResponseBody
	public Filler saveFiller(@RequestBody Filler filler) {
		fillerService.saveFiller(filler);
		return fillerDAO.findFillerByPrimaryKey(filler.getId());
	}

	@RequestMapping(value = "/restSaveFiller", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveFiller(@RequestBody String fillerJson) {
		Filler filler = new Gson().fromJson(fillerJson, Filler.class);
		appendReferences(filler);
		CmiPsonService cmiPsonService = new CmiPsonService();
		fillerService.saveFiller(filler);
		return JSONObject.parse(cmiPsonService.toJsonString(fillerDAO.findFillerByPrimaryKey(filler.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteFiller/{fillerId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteFiller(@PathVariable Integer fillerId) {
		Filler filler = fillerDAO.findFillerByPrimaryKey(fillerId);
		fillerService.deleteFiller(filler);
	}

	@RequestMapping(value = "/restConfirmDeleteFillers")
	@ResponseBody
	public Object restConfirmDeleteFillers(@RequestBody Set<Integer> deleteFillersIds) {
		Set<Filler> deleteFillers = fillerDAO.findFillersByIds(deleteFillersIds);
		Set<Filler> referencedFillers = fillerService.loadReferenceFillers(deleteFillers);
		deleteFillers.removeAll(referencedFillers);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedFillers);
		jsonObject.put("deleteEntitys", deleteFillers);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteFillers")
	@ResponseBody
	public Object restDeleteFillers(@RequestBody Set<Filler> deleteFillers) {
		Iterator<Filler> iterator = deleteFillers.iterator();
		while (iterator.hasNext()) {
			Filler currentFiller = iterator.next();
			fillerService.deleteFiller(currentFiller);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listFillers");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadFiller/{fillerId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFiller(@PathVariable Integer fillerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(fillerDAO.findFillerByPrimaryKey(fillerId), 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFillerFillertype/{fillerId}/fillertype", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFillerFillertype(@PathVariable Integer fillerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(fillerDAO.findFillerByPrimaryKey(fillerId).getFillertype(), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadFillerFillerfillersForOther/{fillerId}/fillerfillersForOther/{relatedfillerfillerId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFillerFillerfillersForOther(@PathVariable Integer fillerId,
			@PathVariable Integer relatedfillerfillerId, @RequestBody CmiPagination cmiPagination) {
		Fillerfiller fillerfiller = fillerfillerDAO.findFillerfillerByPrimaryKey(relatedfillerfillerId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(fillerfiller, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFillerFillerfillersForSelf/{fillerId}/fillerfillersForSelf/{relatedfillerfillerId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFillerFillerfillersForSelf(@PathVariable Integer fillerId,
			@PathVariable Integer relatedfillerfillerId, @RequestBody CmiPagination cmiPagination) {
		Fillerfiller fillerfiller = fillerfillerDAO.findFillerfillerByPrimaryKey(relatedfillerfillerId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(fillerfiller, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFillerFillerhazards/{fillerId}/fillerhazards/{relatedfillerhazardId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFillerFillerhazards(@PathVariable Integer fillerId,
			@PathVariable Integer relatedfillerhazardId, @RequestBody CmiPagination cmiPagination) {
		Fillerhazard fillerhazard = fillerhazardDAO.findFillerhazardByPrimaryKey(relatedfillerhazardId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(fillerhazard, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadFillerFoodbatchfillers/{fillerId}/foodbatchfillers/{relatedfoodbatchfillerId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadFillerFoodbatchfillers(@PathVariable Integer fillerId,
			@PathVariable Integer relatedfoodbatchfillerId, @RequestBody CmiPagination cmiPagination) {
		Foodbatchfiller foodbatchfiller = foodbatchfillerDAO.findFoodbatchfillerByPrimaryKey(relatedfoodbatchfillerId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodbatchfiller, 2, cmiPagination));
	}

	public void appendReferences(Filler filler) {

		Fillertype fillertype = filler.getFillertype();
		if (fillertype != null)
			filler.setFillertype(fillertypeService.findFillertypeByPrimaryKey(fillertype.getId()));

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Fillerfiller> fillerfillersForOther = new HashSet<>();
		for (Fillerfiller fillerfiller_Other : filler.getFillerfillersForOther()) {
			fillerfillersForOther.add(fillerfillerService.findFillerfillerByPrimaryKey(fillerfiller_Other.getId()));
		}
		filler.setFillerfillersForOther(fillerfillersForOther);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Fillerfiller> fillerfillersForSelf = new HashSet<>();
		for (Fillerfiller fillerfiller_Self : filler.getFillerfillersForSelf()) {
			fillerfillersForSelf.add(fillerfillerService.findFillerfillerByPrimaryKey(fillerfiller_Self.getId()));
		}
		filler.setFillerfillersForSelf(fillerfillersForSelf);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Fillerhazard> fillerhazardsForFiller = new HashSet<>();
		for (Fillerhazard fillerhazard_Filler : filler.getFillerhazardsForFiller()) {
			fillerhazardsForFiller.add(fillerhazardService.findFillerhazardByPrimaryKey(fillerhazard_Filler.getId()));
		}
		filler.setFillerhazardsForFiller(fillerhazardsForFiller);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodbatchfiller> foodbatchfillersForFiller = new HashSet<>();
		for (Foodbatchfiller foodbatchfiller_Filler : filler.getFoodbatchfillersForFiller()) {
			foodbatchfillersForFiller
					.add(foodbatchfillerService.findFoodbatchfillerByPrimaryKey(foodbatchfiller_Filler.getId()));
		}
		filler.setFoodbatchfillersForFiller(foodbatchfillersForFiller);
	}

	@RequestMapping(value = "/restGetFillerFillertype/{fillerId}/fillertype", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFillerFillertype(@PathVariable Integer fillerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(
				cmiPsonService.toPsonString(fillerDAO.findFillerByPrimaryKey(fillerId).getFillertype(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFillerFillerfillersForOther/{fillerId}/fillerfillersForOther", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFillerFillerfillersForOther(@PathVariable Integer fillerId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(fillerDAO.findFillerByPrimaryKey(fillerId).getFillerfillersForOther(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFillerFillerfillersForSelf/{fillerId}/fillerfillersForSelf", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFillerFillerfillersForSelf(@PathVariable Integer fillerId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(fillerDAO.findFillerByPrimaryKey(fillerId).getFillerfillersForSelf(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFillerFillerhazards/{fillerId}/fillerhazards", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFillerFillerhazards(@PathVariable Integer fillerId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(fillerDAO.findFillerByPrimaryKey(fillerId).getFillerhazardsForFiller(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetFillerFoodbatchfillers/{fillerId}/foodbatchfillers", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetFillerFoodbatchfillers(@PathVariable Integer fillerId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService
				.toPsonString(fillerDAO.findFillerByPrimaryKey(fillerId).getFoodbatchfillersForFiller(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListFillers", method = RequestMethod.GET)
	@ResponseBody
	public Object restListFillers() {
		return JSONObject.parse(cmiPsonService.toJsonString(fillerService.loadFillers(), 2));
	}

	@RequestMapping(value = "/restListFillersPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListFillersPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = fillerPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Filler> fillers = fillerDAO.findAllFillers(startResult, cmiPagination.getPaginationSize());
		String fillerString = cmiPsonService.toPsonString(fillers, 2, cmiPagination);

		return JSONObject.parse(fillerString);
	}

	@RequestMapping("/fillerSelectBox")
	@ResponseBody
	public JSONObject fillerSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键
			case "Fillertype":
				entitySet = fillertypeService.loadFillertypesByIdSet(searchValue);
				break;

			// 被引用键
			case "Fillerfiller":
				entitySet = fillerfillerService.loadFillerfillersByIdSet(searchValue);
				break;
			case "Fillerhazard":
				entitySet = fillerhazardService.loadFillerhazardsByIdSet(searchValue);
				break;
			case "Foodbatchfiller":
				entitySet = foodbatchfillerService.loadFoodbatchfillersByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键
			case "Fillertype":
				entitySet = fillertypeDAO.findAllFillertypes((pageNumber - 1) * paginationSize, paginationSize);
				count = fillertypeService.countFillertypes();
				break;

			// 被引用键
			case "Fillerfiller":
				entitySet = fillerfillerDAO.findAllFillerfillers((pageNumber - 1) * paginationSize, paginationSize);
				count = fillerfillerService.countFillerfillers();
				break;
			case "Fillerhazard":
				entitySet = fillerhazardDAO.findAllFillerhazards((pageNumber - 1) * paginationSize, paginationSize);
				count = fillerhazardService.countFillerhazards();
				break;
			case "Foodbatchfiller":
				entitySet = foodbatchfillerDAO.findAllFoodbatchfillers((pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchfillerService.countFoodbatchfillers();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键
			case "Fillertype":
				entitySet = fillertypeDAO.findFillertypeByNameContaining(queryword, (pageNumber - 1) * paginationSize,
						paginationSize);
				count = fillertypeService.countFillertypesByName(queryword);
				break;

			// 被引用键
			case "Fillerfiller":
				entitySet = fillerfillerDAO.findFillerfillerByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = fillerfillerService.countFillerfillersByName(queryword);
				break;
			case "Fillerhazard":
				entitySet = fillerhazardDAO.findFillerhazardByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = fillerhazardService.countFillerhazardsByName(queryword);
				break;
			case "Foodbatchfiller":
				entitySet = foodbatchfillerDAO.findFoodbatchfillerByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchfillerService.countFoodbatchfillersByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
